# -*- coding: utf-8 -*-
"""
-----------------------------------------------------------------
    File Name   : file_util.py
    Description : 文件处理工具
    Author      : DuanGe
    Created On  : 2024/11/19
    Email       : duangeali@aliyun.com
    Version     : 1.0.0
    Copyright   : Copyright (c) 2024 DuanGe
    License     : Apache License 2.0
-----------------------------------------------------------------
"""
import json
import os
import shutil

from common.common import error_tip
from common.log import file_logger, add_logs


def _open_file(file_path: str, mode: str = 'r', encoding: str = 'utf-8', is_json: bool = True):
    """
    从指定路径读取文件内容

    :param file_path: 文件路径
    :param mode: 读入模式
    :param encoding: 文件编码
    :param is_json: JSON格式读入
    :return 读取的内容
    """
    operation = "读取文件"
    msg = f"路径: {file_path}, 模式: {mode}, 编码: {encoding}, JSON格式读入: {is_json}"
    try:
        with open(file_path, mode, encoding=encoding) as file:
            if is_json:
                data = json.load(file)
            else:
                data = file.read()
        # 记录日志
        add_logs(file_logger, "INFO", operation, msg)
        return data
    except (FileNotFoundError, PermissionError, IsADirectoryError, OSError, ValueError, UnicodeDecodeError,
            json.JSONDecodeError, Exception) as e:
        err_msg = {
            FileNotFoundError: "文件不存在",
            PermissionError: "没有权限访问文件",
            IsADirectoryError: "是一个目录无法读入",
            OSError: "发生OS错误",
            ValueError: "无效的模式",
            UnicodeDecodeError: f"内容无法用{encoding}解码",
            json.JSONDecodeError: "内容不是有效的JSON格式",
            Exception: "发生未知错误"
        }.get(type(e), "发生未知错误")
        error_tip(f"{operation}失败, {err_msg}")
        # 记录日志
        add_logs(file_logger, "ERROR", operation, msg, err_msg, e)
        return None


def _write_file(file_path: str, content: any, mode: str = 'w', encoding: str = 'utf-8', is_json: bool = True,
                indent: int = 2):
    """
    将内容写入到指定路径的文件中

    :param file_path: 文件路径
    :param content: 写入的数据
    :param mode: 写入模式
    :param encoding: 文件编码
    :param is_json: JSON格式写入
    :param indent: JSON缩进
    :return 操作结果
    """
    operation = "写入文件"
    msg = f"路径: {file_path}, 模式: {mode}, 编码: {encoding}, JSON格式写入: {is_json}, JSON缩进: {indent}"
    try:
        with open(file_path, mode, encoding=encoding) as file:
            if is_json:
                json.dump(content, file, ensure_ascii=False, indent=indent)
            else:
                file.write(content)
        # 记录日志
        add_logs(file_logger, "INFO", operation, msg)
        return True
    except (FileNotFoundError, PermissionError, IsADirectoryError, OSError, ValueError, TypeError, IOError,
            UnicodeEncodeError, Exception) as e:
        err_msg = {
            FileNotFoundError: "文件路径所在目录不存在",
            PermissionError: "没有权限写入文件",
            IsADirectoryError: "是一个目录无法写入",
            OSError: "发生OS错误",
            ValueError: "无效的模式",
            TypeError: "内容类型错误",
            IOError: "发生IO错误",
            UnicodeEncodeError: f"内容无法用{encoding}编码",
            Exception: "发生未知错误"
        }.get(type(e), "发生未知错误")
        error_tip(f"{operation}失败, {err_msg}")
        # 记录日志
        add_logs(file_logger, "ERROR", operation, msg, err_msg, e)
        return False


def read_file(file_path: str, mode: str = 'r', encoding: str = 'utf-8'):
    """
    从指定路径读取文件内容

    :param file_path: 文件路径
    :param mode: 读入模式
    :param encoding: 文件编码
    :return 读取的内容
    """
    return _open_file(file_path=file_path, mode=mode, encoding=encoding, is_json=False)


def read_json(file_path: str, mode: str = 'r', encoding: str = 'utf-8'):
    """
    从指定路径读取 JSON 文件并返回解析后的数据

    :param file_path: 文件路径
    :param mode: 读入模式
    :param encoding: 文件编码
    :return 读取的内容
    """
    return _open_file(file_path=file_path, mode=mode, encoding=encoding)


def write_file(file_path: str, content: any, mode: str = 'w', encoding: str = 'utf-8'):
    """
    将内容写入到指定路径的文件中

    :param file_path: 文件路径
    :param content: 写入的数据
    :param mode: 写入模式
    :param encoding: 文件编码
    :return 操作结果
    """
    return _write_file(file_path=file_path, content=content, mode=mode, encoding=encoding, is_json=False)


def write_json(file_path: str, content: any, mode: str = 'w', encoding: str = 'utf-8', indent: int = 2):
    """
    将数据以 JSON 格式写入到指定路径的文件中

    :param file_path: 文件路径
    :param content: 写入的数据
    :param mode: 写入模式
    :param encoding: 文件编码
    :param indent: JSON缩进
    :return 操作结果
    """
    return _write_file(file_path=file_path, content=content, mode=mode, encoding=encoding, indent=indent)


def create_directory(directory_path: str):
    """
    创建目录

    :param directory_path: 目录路径
    :return 操作结果
    """
    operation = "创建目录"
    msg = f"路径: {directory_path}"
    try:
        os.makedirs(directory_path)
        # 记录日志
        add_logs(file_logger, "INFO", operation, msg)
        return True
    except (FileExistsError, PermissionError, OSError, ValueError, Exception) as e:
        err_msg = {
            FileExistsError: "目录已存在",
            PermissionError: "没有权限创建目录",
            OSError: "发生OS错误",
            ValueError: "无效的路径",
            Exception: "发生未知错误"
        }.get(type(e), "发生未知错误")
        error_tip(f"{operation}失败, {err_msg}")
        # 记录日志
        add_logs(file_logger, "ERROR", operation, msg, err_msg, e)
        return False


def delete_file(file_path: str):
    """
    删除指定路径的文件

    :param file_path: 文件路径
    :return: 操作结果
    """
    operation = "删除文件"
    msg = f"路径: {file_path}"
    try:
        os.remove(file_path)
        # 记录日志
        add_logs(file_logger, "INFO", operation, msg)
        return True
    except (FileNotFoundError, PermissionError, IsADirectoryError, OSError, Exception) as e:
        err_msg = {
            FileNotFoundError: "文件不存在",
            PermissionError: "没有权限删除文件",
            IsADirectoryError: "是一个目录无法删除",
            OSError: "发生OS错误",
            Exception: "发生未知错误"
        }.get(type(e), "发生未知错误")
        error_tip(f"{operation}失败, {err_msg}")
        # 记录日志
        add_logs(file_logger, "ERROR", operation, msg, err_msg, e)
        return False


def delete_directory(directory_path: str):
    """
     删除指定路径的目录及其所有内容

     :param directory_path: 目录路径
     :return 操作结果
     """
    operation = "删除目录"
    msg = f"路径: {directory_path}"
    try:
        shutil.rmtree(directory_path)
        # 记录日志
        add_logs(file_logger, "INFO", operation, msg)
        return True
    except (FileNotFoundError, PermissionError, NotADirectoryError, OSError, RuntimeError, Exception) as e:
        err_msg = {
            FileNotFoundError: "目录不存在",
            PermissionError: "没有权限删除目录及其内容",
            NotADirectoryError: "不是一个目录",
            OSError: "发生OS错误",
            RuntimeError: "发生其他运行时错误",
            Exception: "发生未知错误"
        }.get(type(e), "发生未知错误")
        error_tip(f"{operation}失败, {err_msg}")
        # 记录日志
        add_logs(file_logger, "ERROR", operation, msg, err_msg, e)
        return False
